const { vip_member, op } = require('../../middleware/baseModel');

module.exports = {
    'GET /vip_member/all': async (ctx, next) => {
        const res = await vip_member.findAll();
        return ctx.success(res);
    },

    'GET /vip_member/detail': async (ctx, next) => {
        let id = ctx.get('id')
        const res = await vip_member.findOne({ where: { id: id } });
        return ctx.success(res);
    },


    "POST /vip_member/export": async (ctx, next) => {
        let rows = [];
        let cols = [];
        let title = 'vip_member';

        let tableAttributes = vip_member.tableAttributes;
        let colKeys = Object.keys(tableAttributes);

        colKeys.forEach((key) => {
            let row = tableAttributes[key];
            let caption = row.comment ? row.comment : row.fieldName;
            cols.push({ caption, type: row.type.__proto__.key === "INTEGER" ? "number" : "string", key: row.field });
        });

        const dbRows = await vip_member.findAll({});
        rows = dbRows.map((p) => {
            let tempRow = p.toJSON();
            let row = [];
            cols.forEach((col) => {
                row.push(tempRow[col.key]);
            });
            return row;
        });

        return ctx.downFile({ title, rows, cols });
    },

    'POST /vip_member/page': async (ctx, next) => {
        let param = ctx.getPageSize()
        let row = ctx.getBody();
        let { key, value } = row.seachOption
        let where = {}
        if (key && value) {
            where[key] = { [op.like]: '%' + value + '%' }
        }

        const res = await vip_member.findAndCountAll({
            where,
            order: [["id", "DESC"]],
            ...param,
        });
        return ctx.success(res);
    },

    'POST /vip_member/add': async (ctx, next) => {
        let row = ctx.getBody();
        const res = await vip_member.create(row);
        return ctx.success(res);
    },
    'POST /vip_member/edit': async (ctx, next) => {
        let row = ctx.getBody();
        let id = ctx.get('id')
        const res = await vip_member.update(row, { where: { id: id }, individualHooks: true });
        return ctx.success(res);
    },

    'POST /vip_member/del': async (ctx, next) => {
        let id = ctx.get('id')
        const res = await vip_member.destroy({ where: { id: id }, individualHooks: true });
        return ctx.success(res);
    }
};